
function epoch(){
	var today = new Date(); 
	var expiredDate = new Date(today);
	expiredDate.setDate(today.getDate()+1);
	return parseInt((expiredDate.getTime()-expiredDate.getMilliseconds())/1000);
}
function hencode_utf8(string) {
	  return unescape(encodeURIComponent(string));
}
function syncDataWithService(){

	var url  = window.location.href.toString();
	if(!url.indexOf('path') >= 0){
		window.location.href = window.location.href;
	} else {
		getAllDocuments();		
	}
}
function checkModified(lastModified){
	var currentTime = epochExample1();
	var lastModifiedTime = Date.parse(lastModified)/1000;
	if(parseInt(currentTime) < parseInt(lastModifiedTime)){
		syncDataWithService();
		return false;
	}
	return true;
}

function listObjectS3(signature,timeAccess,ASWAccessKeyId,folderOwner,folderPath){
		
		    $.ajax({
		    type: 'GET',
		    url: 'https://s3-ap-southeast-1.amazonaws.com/cloudsharingpublic?prefix='+folderOwner+'/'+encodeURIComponent(folderPath),
		    data: 'AWSAccessKeyId='+ ASWAccessKeyId + '&Expires='+timeAccess+ '&Signature='+signature,
		    datatype:'xml',
		    success: function(data)
		    {
		    	var lastModified;
		    	var previous = parseInt($('input[name="objectKey"]').val());
		    	var current = $(data).find("Contents").size();
		    	console.log(previous + current);
		    	if(previous != current){
		    		syncDataWithService();
		    	}
		    	setTimeout(function(){listObjectS3(signature,timeAccess,ASWAccessKeyId,folderOwner,folderPath);}, 5000);
		    },
		    error: function(e)
		    {
		        alert('Error: ' + e);
		    }
		  });
		    
}
function getObjectFirstTime(signature,timeAccess,ASWAccessKeyId,folderOwner,folderPath){
		
	    $.ajax({
	    type: 'GET',
	    url: 'https://s3-ap-southeast-1.amazonaws.com/cloudsharingpublic?prefix='+folderOwner+'/'+encodeURIComponent(folderPath),
	    data: 'AWSAccessKeyId='+ ASWAccessKeyId + '&Expires='+timeAccess+ '&Signature='+signature,
	    datatype:'xml',
	    success: function(data)
	    {
	    	$('input[name="objectKey"]').val($(data).find("Contents").size());
	    	listObjectS3(signature,timeAccess,ASWAccessKeyId,folderOwner,folderPath);	
	    },
	    error: function(e)
	    {
	        alert('Error: ' + e);
	    }
	  });
	    
}

function syncDataS3(folderPath,folderOwner){
	var timeAccess  = epoch().toString();
	var stringtosign = hencode_utf8("GET\n\n\n"+timeAccess+"\n/cloudsharingpublic");
	var ASWAccessKeyId = 'AKIAJPGSDIIFNSVSL6AA';
	var hash = CryptoJS.HmacSHA1(stringtosign, "BzJXJ1hMKQsRfpfxMZlPbJBlUgcKa3DrKx1iJb+J");
	var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
	var signature = encodeURIComponent(hashInBase64);
	getObjectFirstTime(signature,timeAccess,ASWAccessKeyId,folderOwner,folderPath);
}
  